package com.youyicloud.api;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.youyicloud.entity.EquipmentInfo;
import com.youyicloud.entity.EquipmentPay;
import com.youyicloud.entity.PayInfo;
import com.youyicloud.service.EquipmentPayService;
import com.youyicloud.service.EquipmentService;
import com.youyicloud.service.PayService;
import com.youyicloud.utils.QRCodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

@Controller
@Slf4j
public class QrCodeApi {
    @Autowired
    private EquipmentPayService equipmentPayService;
    @Autowired
    private EquipmentService equipmentService;
    @Autowired
    private PayService payService;

    @RequestMapping("getImage")
    public void getImage(String type,Integer equipmentId,int width,int height,HttpServletResponse response) throws Exception{
        EquipmentPay equipmentPay = equipmentPayService.findByEquipmentId(equipmentId);
        String url = "";
        if(StringUtils.isNotEmpty(type)){
            PayInfo payInfo = payService.findById(equipmentPay.getPayId());
            url = payInfo.getPayUrl()+"/"+payInfo.getEquipmentBrevityCode();
        }else{
            EquipmentInfo equipment = equipmentService.findById(equipmentPay.getEquipmentId());
            url = equipment.getImeiMac();
        }
        if (url != null && !"".equals(url)) {
            ServletOutputStream stream = null;
            try {
                if(width<50){
                    width = 200;//图片的宽度
                }
                if(height<50){
                    height = 200;//图片的宽度
                }
                stream = response.getOutputStream();
                QRCodeWriter writer = new QRCodeWriter();
                BitMatrix m = writer.encode(url, BarcodeFormat.QR_CODE, height, width);
                m = QRCodeUtil.deleteWhite(m);//删除白边
                MatrixToImageWriter.writeToStream(m, "png", stream);
            } catch (WriterException e) {
                e.printStackTrace();
            } finally {
                if (stream != null) {
                    stream.flush();
                    stream.close();
                }
            }
        }
    }
}
